package com.anysoft.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.anysoft.R;

/**
 * 手势密码解锁页
 *
 * @author wangwenqiang
 */
public class ViewLoginNinePointPwd extends View {

    private Paint linePaint = new Paint();

    private Paint whiteLinePaint = new Paint();

    private Paint textPaint = new Paint();

    private Bitmap defaultBitmap = BitmapFactory.decodeResource(getResources(),
            R.mipmap.lock);

    private int defaultBitmapRadius = defaultBitmap.getWidth() / 2;

    private Bitmap selectedBitmap = BitmapFactory.decodeResource(getResources(),
            R.mipmap.indicator_lock_area);

//    private Bitmap selectedCenterBitmap = BitmapFactory.decodeResource(getResources(),
//            R.mipmap.selected);

    private int selectedBitmapDiameter = selectedBitmap.getWidth();

    private int selectedBitmapRadius = selectedBitmapDiameter / 2;

    private PointInfo[] points = new PointInfo[9];

    private PointInfo startPoint = null;

    private int width, height;

    private int moveX, moveY;

    private boolean isUp = false;

    private int selectTimes = 0;

    private Context cxt;

    private StringBuffer lockString = new StringBuffer();

    private OnPwdSetSucessListener onPwdSetSucessListener;

    /**
     * 0:来自登陆，1:来自设置页1,2:来自设置页2
     */
//    private int fromType;

    private int viewWidth, viewHeight;

    public void SetOnPwdSetSucessListener(OnPwdSetSucessListener onPwdSetSucessListener) {
        this.onPwdSetSucessListener = onPwdSetSucessListener;
    }

    public ViewLoginNinePointPwd(Context context, /*int fromType,*/ int viewWidth, int viewHeight) {

        super(context);
        cxt = context;
//        this.fromType = fromType;
        this.viewWidth = viewWidth;
        this.viewHeight = viewHeight;
        // this.setBackgroundColor(Color.WHITE);//设置整个背景
        initPaint();
    }

    public ViewLoginNinePointPwd(Context context, AttributeSet attrs) {

        super(context, attrs);
        // this.setBackgroundColor(Color.WHITE);//设置整个九宫格的背景
        initPaint();
    }

    /**
     * 获取布局的宽、高，来设置九宫格位置
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        // width = getWidth();
        // height = getHeight();

//        switch (fromType) {
//            case 0:
//                width = LoginByGestureActivity.PWD_WIDTH;
//                height = LoginByGestureActivity.PWD_HEIGHT;
//                break;
//            case 1:
//                width = SetGestureStep1Activity.PWD_WIDTH;
//                height = SetGestureStep1Activity.PWD_HEIGHT;
//                break;
//            case 2:
//                width = SetGestureStep2Activity.PWD_WIDTH;
//                height = SetGestureStep2Activity.PWD_HEIGHT;
//                break;
//            default:
//                break;
//        }

        width = viewWidth;
        height = viewHeight;

        if (width != 0 && height != 0) {
            initPoints(points);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    private int startX = 0, startY = 0;

    @Override
    protected void onDraw(Canvas canvas) {

        // canvas.drawText("passwd:" + lockString, 0, 40, textPaint);

        if (moveX != 0 && moveY != 0 && startX != 0 && startY != 0) {
            // drawLine(canvas, startX, startY, moveX, moveY);
        }
        drawNinePoint(canvas);
        super.onDraw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {

            case MotionEvent.ACTION_MOVE:

                moveX = (int) event.getX();
                moveY = (int) event.getY();

                for (PointInfo temp : points) {
                    if (temp.isInMyPlace(moveX, moveY)
                            && temp.isSelected() == false) {
                        selectTimes++;
                        temp.setSelected(true);

                        if (selectTimes == 1) {
                            startPoint = temp;
                        }

                        startX = temp.getCenterX();
                        startY = temp.getCenterY();
                        int len = lockString.length();

                        if (len != 0) {
                            int preId = lockString.charAt(len - 1) - 48;
                            points[preId].setNextId(temp.getId());
                        }

                        lockString.append(temp.getId());

                        break;
                    }
                }
                // 刷新局部，四个参数分别为左、上、右、下
                invalidate(0, height - width, width, height);
                break;

            case MotionEvent.ACTION_DOWN:
                break;

            case MotionEvent.ACTION_UP:

                startX = startY = moveX = moveY = 0;
                invalidate();

                if (!TextUtils.isEmpty(this.getPwd())) {
                    if (this.getPwd().length() < 4) {
                        if (this.getPwd().length() > 1) {
                            Toast.makeText(cxt, "密码位数小于4，请重试", Toast.LENGTH_LONG)
                                    .show();
                        }
                    } else {
                        savePwd();
                    }
                } else {
//                    Toast.makeText(cxt, "密码不能为空，请重试", Toast.LENGTH_LONG)
//                            .show();
                }

                selectTimes = 0;
                finishDraw();
                break;

            default:
                break;
        }
        return true;
    }

    private void finishDraw() {

        for (PointInfo temp : points) {
            temp.setSelected(false);
            temp.setNextId(temp.getId());
        }
        lockString.delete(0, lockString.length());
        isUp = false;
        invalidate();
    }

    private void initPoints(PointInfo[] points) {

        int len = points.length;
        int seletedSpacing = 0;
        int seletedX = 0;
        int seletedY = 0;
        int defaultX = 0;
        int defaultY = 0;
        //System.out.println("height--" + height + ",width--" + width);
        if (height < width) {
            seletedSpacing = (height - selectedBitmapDiameter * 3) / 4;
            seletedX = (width - height) / 4 + seletedSpacing;
            seletedY = seletedSpacing;
            defaultX = seletedX + selectedBitmapRadius - defaultBitmapRadius;
            defaultY = seletedY + selectedBitmapRadius - defaultBitmapRadius;

            for (int i = 0; i < len; i++) {
                if (i == 3 || i == 6) {
                    seletedX = (width - height) / 2 + seletedSpacing;
                    seletedY += selectedBitmapDiameter + seletedSpacing;
                    defaultX = seletedX + selectedBitmapRadius
                            - defaultBitmapRadius;
                    defaultY += selectedBitmapDiameter + seletedSpacing;
                }
                points[i] = new PointInfo(i, defaultX, defaultY, seletedX,
                        seletedY);
                seletedX += selectedBitmapDiameter + seletedSpacing;
                defaultX += selectedBitmapDiameter + seletedSpacing;
            }
        } else {
            seletedSpacing = (width - selectedBitmapDiameter * 3) / 4;
            seletedX = seletedSpacing;
            seletedY = (width - height) / 4 + seletedSpacing;
//            seletedY = height - width + seletedSpacing;
            defaultX = seletedX + selectedBitmapRadius - defaultBitmapRadius;
            defaultY = seletedY + selectedBitmapRadius - defaultBitmapRadius;

            for (int i = 0; i < len; i++) {
                if (i == 3 || i == 6) {
                    seletedX = seletedSpacing;
                    seletedY += selectedBitmapDiameter + seletedSpacing;
                    defaultX = seletedX + selectedBitmapRadius
                            - defaultBitmapRadius;
                    defaultY += selectedBitmapDiameter + seletedSpacing;
                }
                points[i] = new PointInfo(i, defaultX, defaultY, seletedX,
                        seletedY);
                seletedX += selectedBitmapDiameter + seletedSpacing;
                defaultX += selectedBitmapDiameter + seletedSpacing;
            }
        }

    }

    private void initPaint() {
        initTextPaint(textPaint);
        initWhiteLinePaint(whiteLinePaint);
    }

    /**
     * @param paint
     */
    private void initTextPaint(Paint paint) {
        textPaint.setTextSize(30);
        textPaint.setAntiAlias(true);
        textPaint.setTypeface(Typeface.MONOSPACE);
    }

    /**
     * @param paint
     */
    private void initWhiteLinePaint(Paint paint) {
        paint.setColor(getResources().getColor(R.color.bg_btn_red));
        paint.setStrokeWidth(10);// 设置两个点之间的线的宽度
        paint.setAntiAlias(true);
        paint.setStrokeCap(Cap.ROUND);
    }

    /**
     * @param canvas
     */
    private void drawNinePoint(Canvas canvas) {

        if (startPoint != null) {
            drawEachLine(canvas, startPoint);
        }

        for (PointInfo pointInfo : points) {
            if (pointInfo != null) {
                if (!pointInfo.isSelected()) {
                    canvas.drawBitmap(defaultBitmap, pointInfo.getDefaultX(),
                            pointInfo.getDefaultY(), null);
                } else {
//                    canvas.drawBitmap(selectedCenterBitmap,
//                            pointInfo.getSeletedX(), pointInfo.getSeletedY(),
//                            null);
                    canvas.drawBitmap(selectedBitmap, pointInfo.getSeletedX(),
                            pointInfo.getSeletedY(), null);
                }

            }
        }

    }

    /**
     * @param canvas
     * @param point
     */
    private void drawEachLine(Canvas canvas, PointInfo point) {

        if (point.hasNextId()) {
            int n = point.getNextId();
            drawLine(canvas, point.getCenterX(), point.getCenterY(),
                    points[n].getCenterX(), points[n].getCenterY());
            drawEachLine(canvas, points[n]);
        }
    }

    /**
     * @param canvas
     * @param startX
     * @param startY
     * @param stopX
     * @param stopY
     */
    private void drawLine(Canvas canvas, float startX, float startY,
                          float stopX, float stopY) {
        canvas.drawLine(startX, startY, stopX, stopY, linePaint);
        canvas.drawLine(startX, startY, stopX, stopY, whiteLinePaint);
    }

    private class PointInfo {

        private int id;
        private int nextId;
        private boolean selected;
        private int defaultX;
        private int defaultY;
        private int seletedX;
        private int seletedY;

        public PointInfo(int id, int defaultX, int defaultY, int seletedX,
                         int seletedY) {
            this.id = id;
            this.nextId = id;
            this.defaultX = defaultX;
            this.defaultY = defaultY;
            this.seletedX = seletedX;
            this.seletedY = seletedY;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }

        public int getId() {
            return id;
        }

        public int getDefaultX() {
            return defaultX;
        }

        public int getDefaultY() {
            return defaultY;
        }

        public int getSeletedX() {
            return seletedX;
        }

        public int getSeletedY() {
            return seletedY;
        }

        public int getCenterX() {
            return seletedX + selectedBitmapRadius;
        }

        public int getCenterY() {
            return seletedY + selectedBitmapRadius;
        }

        public boolean hasNextId() {
            return nextId != id;
        }

        public int getNextId() {
            return nextId;
        }

        public void setNextId(int nextId) {
            this.nextId = nextId;
        }

        /**
         * @param x
         * @param y
         */
        public boolean isInMyPlace(int x, int y) {
            boolean inX = x > seletedX
                    && x < (seletedX + selectedBitmapDiameter);
            boolean inY = y > seletedY
                    && y < (seletedY + selectedBitmapDiameter);
            return (inX && inY);
        }
    }

    public String getPwd() {// 获取本次的密码
        return TextUtils.isEmpty(lockString.toString()) ? "" : lockString.toString();
    }

    /**
     * 作用：保存密码并且判断界面的跳转
     */
    public void savePwd() {
        if (onPwdSetSucessListener != null) {
            onPwdSetSucessListener.OnPwdSetSucessListener(getPwd());
        }
    }

    public interface OnPwdSetSucessListener {

        /**
         * @param password
         */
        void OnPwdSetSucessListener(String password);
    }

}
